﻿using System;
using System.IO;
using System.Text;

namespace ItemQuoteLibrary
{
    class ItemQuoteEncoderText:ItemQuoteEncoder
    {
        public Encoding EncodingType { get; private set; }

        public ItemQuoteEncoderText(string encodingType)
        {
            EncodingType = Encoding.GetEncoding(encodingType);
        }

        public ItemQuoteEncoderText()
            :this(ItemQuoteTextConst.DEFAULT_CHAR_ENC)
        {            
        }

        public byte[] Encode(ItemQuote item)
        {
            StringBuilder encodedString = new StringBuilder();
            encodedString.Append(item.ItemNumber + " ");

            if (item.ItemDescription.IndexOf("\n") != -1)
                throw new IOException("Invalid item description");

            encodedString.Append(item.ItemDescription + "\n");
            encodedString.Append(item.Quantity + " ");
            encodedString.Append(item.UnitPrice + " ");

            if (item.Discounted)
                encodedString.Append("d");
            if (item.InStock)
                encodedString.Append("s");

            encodedString.Append("\n");

            if (encodedString.Length > ItemQuoteTextConst.MAX_WIRE_LENGTH)
                throw new IOException("Encoded length is too long");

            byte[] buffer = EncodingType.GetBytes(encodedString.ToString());

            return buffer;
        }
    }
}
